package com.meirengu.webview.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.meirengu.common.RedisClient;
import com.meirengu.common.StatusCode;
import com.meirengu.model.Result;
import com.meirengu.utils.MD5Util;
import com.meirengu.utils.RequestUtil;
import com.meirengu.webview.service.UserService;
import com.meirengu.webview.utils.ConfigUtil;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.*;

@Controller
@RequestMapping("sh")
public class StorehouseController extends BaseController {

    Logger logger = LoggerFactory.getLogger(StorehouseController.class);


    @Autowired
    private UserService userService;
    @Autowired
    private RedisClient redisClient;

    /**
     * 初始化手机号的MD5值到redis中
     *
     * @param createTimeBegin
     * @param createTimeEnd
     * @return
     */
    @RequestMapping("initRedisMobile")
    @ResponseBody
    public Result initStorehouse(@RequestParam(value = "createTimeBegin", required = true) String createTimeBegin,
                                 @RequestParam(value = "createTimeEnd", required = true) String createTimeEnd) {
        if (StringUtils.isBlank(createTimeBegin) || StringUtils.isBlank(createTimeEnd)) {
            return setResult(StatusCode.MISSING_ARGUMENT, null, StatusCode.codeMsgMap.get(StatusCode.MISSING_ARGUMENT));
        }
        //查出符合条件的用户
        Map<String, Object> map = new HashMap<>();
        if (StringUtils.isNotBlank(createTimeBegin)) {
            map.put("createTimeBegin", createTimeBegin);
        }
        if (StringUtils.isNotBlank(createTimeEnd)) {
            map.put("createTimeEnd", createTimeEnd);
        }
        try {
            List<Map<String, Object>> userList = userService.getList(map);
            if (userList != null && userList.size() > 0) {
                for (Map<String, Object> userMap : userList) {
                    String mobile = (String) userMap.get("mobile");
                    if (StringUtils.isNotBlank(mobile)) {
                        String onceMd5 = MD5Util.MD5(mobile, "utf-8");
                        String twiceMd5 = MD5Util.MD5(onceMd5, "utf-8");
                        logger.info("StorehouseController.initRedisMobile===>twiceMd5:{}.", twiceMd5);
                        redisClient.sadd("Md5Mobile", twiceMd5);
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            logger.error(ExceptionUtils.getFullStackTrace(e));
            return setResult(StatusCode.INTERNAL_SERVER_ERROR, null, StatusCode.codeMsgMap.get(StatusCode.INTERNAL_SERVER_ERROR));
        }
        return setResult(StatusCode.OK, null, StatusCode.codeMsgMap.get(StatusCode.OK));
    }

    /**
     * 传单个MD5
     *
     * @param param
     * @param request
     * @return
     */
    @RequestMapping("shSingle")
    @ResponseBody
    public Result storeHouseSingle(@RequestBody String param, HttpServletRequest request) {
        Result result = new Result();
        String ip = RequestUtil.getClientIp(request);
        logger.info("StorehouseController.searchIp===>ip:{}.", ip);
        if (!redisClient.sismember("IPWHITESET", ip)) {
            return setResult(StatusCode.IP_NOT_ALLOWED, null, StatusCode.codeMsgMap.get(StatusCode.IP_NOT_ALLOWED));
        }
        JSONObject jsonObject = JSON.parseObject(param);
        String md5Mobile = jsonObject.getString("mobile");
        redisClient.sadd("saveMdMobile", md5Mobile);
        try {
            if (StringUtils.isBlank(md5Mobile)) {
                return setResult(StatusCode.MISSING_ARGUMENT, null, StatusCode.codeMsgMap.get(StatusCode.MISSING_ARGUMENT));
            }
            logger.info("StorehouseController.shSingle===>Md5:{}.", md5Mobile);
            //判断是否存在 拼接标识后返回
            boolean flag = redisClient.sismember("Md5Mobile", md5Mobile);
            if (flag) {
                result.setData(md5Mobile + ":1");
            } else {
                result.setData(md5Mobile + ":0");
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(ExceptionUtils.getFullStackTrace(e));
            return setResult(StatusCode.INTERNAL_SERVER_ERROR, null, StatusCode.codeMsgMap.get(StatusCode.INTERNAL_SERVER_ERROR));
        }
        result.setCode(StatusCode.OK);
        result.setMsg(StatusCode.codeMsgMap.get(StatusCode.OK));
        return result;
    }

    /**
     * 传多个MD5 按逗号分隔
     *
     * @param params
     * @param request
     * @return
     */
    @RequestMapping("shBatch")
    @ResponseBody
    public Result storeHouseBatch(@RequestBody String params, HttpServletRequest request) {
        Result result = new Result();
        JSONObject jsonObject = JSON.parseObject(params);
        String md5MobileStr = jsonObject.getString("mobile");
        String ip = RequestUtil.getClientIp(request);
        logger.info("StorehouseController.shBatch===>params:{}.", params);
        logger.info("StorehouseController.searchIp===>ip:{}.", ip);
        if (!redisClient.sismember("IPWHITESET", ip)) {
            return setResult(StatusCode.IP_NOT_ALLOWED, null, StatusCode.codeMsgMap.get(StatusCode.IP_NOT_ALLOWED));
        }
        try {
            if (StringUtils.isBlank(md5MobileStr)) {
                return setResult(StatusCode.MISSING_ARGUMENT, null, StatusCode.codeMsgMap.get(StatusCode.MISSING_ARGUMENT));
            }

            if (md5MobileStr.contains(",")) {
                // 按逗号分隔字符串 遍历数组 如果字符串长度不等于32则跳过本次循环
                String Md5KeyName = "Md5Mobile";
                String keyName = ip + new Date().getTime();
                String[] strs = md5MobileStr.split(",");
                List<String> list = new ArrayList<>();
                Set<String> set = new HashSet<>();
                Set<String> dset = new HashSet<>();
                Set<String> iset = new HashSet<>();
                A:
                for (String str : strs) {
                    redisClient.sadd("saveMdMobile", str);
                    if (str.length() != 32) {
                        continue A;
                    }
                    set.add(str);
                }
                redisClient.sadd(keyName, set);
                dset = redisClient.sdiff(keyName, Md5KeyName);
                iset = redisClient.sinter(keyName, Md5KeyName);
                for (String str : dset) {
                    str = str + ":0";
                    list.add(str);
                }
                for (String str : iset) {
                    str = str + ":1";
                    list.add(str);
                }
                result.setData(list);
                redisClient.remove(keyName);
                //对单个手机号的校验
            } else if (md5MobileStr.length() == 32) {
                boolean flag = redisClient.sismember("Md5Mobile", md5MobileStr);
                if (flag) {
                    result.setData(md5MobileStr + ":1");
                } else {
                    result.setData(md5MobileStr + ":0");
                }
                //格式错误的数据进行统一返回
            } else {
                return setResult(StatusCode.MISSING_ARGUMENT, null, StatusCode.codeMsgMap.get(StatusCode.MISSING_ARGUMENT));
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(ExceptionUtils.getFullStackTrace(e));
            return setResult(StatusCode.INTERNAL_SERVER_ERROR, null, StatusCode.codeMsgMap.get(StatusCode.INTERNAL_SERVER_ERROR));
        }
        result.setCode(StatusCode.OK);
        result.setMsg(StatusCode.codeMsgMap.get(StatusCode.OK));
        return result;
    }

    /**
     * 导出redis手机号数据
     */
    @RequestMapping("exportTxt")
    @ResponseBody
    public void exportTxt() {
        logger.info("===================>进入方法数据");
        Set<String> strs = redisClient.smembers("saveMdMobile1");
        StringBuffer sb = new StringBuffer();
        BufferedWriter out = null;
        logger.info("===================>已读取数据");
        int a = 0;
        try {
            if (strs.size() > 0) {
                String fileName = "exportMobile.txt";
                String relFilePath = ConfigUtil.getConfig("LOG_HOME") + File.separator + fileName;
                File file = new File(relFilePath);
                if (!file.exists()) {
                    file.createNewFile();
                }
                out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8"));
                logger.info("===================>循环拼接");
                for (String str : strs) {
                    a++;
                    sb.append(str + "," + "\r\n");
                }
                logger.info("===================>准备写入方法");
                out.write(sb.substring(0, sb.length() - 1) + "===>总数" + a);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.flush();
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 导出redis手机号数据
     */
    @RequestMapping("exportTxt2")
    @ResponseBody
    public void exportTxt2() {
        logger.info("===================>进入方法数据");
        Set<String> strs = redisClient.sdiff("saveMdMobile", "saveMdMobile1");
        logger.info("===============" + strs.size());
        StringBuffer sb = new StringBuffer();
        BufferedWriter out = null;
        logger.info("===================>已读取数据");
        int a = 0;
        try {
            if (strs.size() > 0) {
                String fileName = "exportMobile2.txt";
                String relFilePath = ConfigUtil.getConfig("LOG_HOME") + File.separator + fileName;
                File file = new File(relFilePath);
                if (!file.exists()) {
                    file.createNewFile();
                }
                out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8"));
                logger.info("===================>循环拼接");
                for (String str : strs) {
                    a++;
                    sb.append(str + "," + "\r\n");
                }
                logger.info("===================>准备写入方法");
                out.write(sb.substring(0, sb.length() - 1) + "===>总数" + a);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.flush();
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


}

